package com.it.feign.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced // 支持Nacos等注册中心的服务名调用, 支持负载均衡
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add(new MockLoggingInterceptor()); // 添加日志拦截器
        restTemplate.setErrorHandler(new CustomResponseErrorHandler() {
        });
        return restTemplate;
    }


    /**
     * 模拟拦截器 - 打印请求/响应日志
     */
    @Slf4j
    public static class MockLoggingInterceptor implements ClientHttpRequestInterceptor {

        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

            // 1. 记录请求信息
            logRequest(request, body);

            // 2. 执行请求
            ClientHttpResponse response = execution.execute(request, body);

            // 3. 记录响应信息
            logResponse(response);

            return response;
        }

        private void logRequest(HttpRequest request, byte[] body) {
            log.info("request URL   : {}", request.getURI());
            log.info("request Method: {}", request.getMethod());
            log.info("request Headers: {}", request.getHeaders());
            if (body.length > 0) {
                log.info("Body  : {}", new String(body, StandardCharsets.UTF_8));
            }
        }

        private void logResponse(ClientHttpResponse response) throws IOException {
            log.info("response Status: {}", response.getStatusCode());
            log.info("response Headers: {}", response.getHeaders());
            // 注意：响应Body只能读取一次，实际使用时需缓存
        }
    }

    // 自定义错误处理器
    public static class CustomResponseErrorHandler extends DefaultResponseErrorHandler {
        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            // 可以在这里实现自定义的错误处理逻辑
            // 默认实现会抛出HttpClientErrorException或HttpServerErrorException
            super.handleError(response);
        }
    }
}
